//
//  ImageTableViewCell.m
//  YHtableViewCellHeightDemo
//
//  Created by apple on 17/4/17.
//  Copyright © 2017年 wax. All rights reserved.
//

#import "ImageTableViewCell.h"

@interface ImageTableViewCell ()

@property (weak, nonatomic) IBOutlet UILabel *keyLabel;

@property (weak, nonatomic) IBOutlet UIView *imagesView;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imagesViewHeight;

@end

@implementation ImageTableViewCell

#define  ScreenW [UIScreen mainScreen].bounds.size.width

#define  ScreenH [UIScreen mainScreen].bounds.size.height


- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

+(instancetype)loadCell{

    return [[NSBundle mainBundle] loadNibNamed:@"ImageTableViewCell" owner:nil options:nil].lastObject;
    
}

#pragma mark - setValue
-(void)setDataDic:(NSDictionary *)dataDic{


    _dataDic = dataDic;
    
    _keyLabel.text = dataDic[@"myKey"];
    
    //动态创建按钮 --> 暂定：假设创建按钮，根据按钮数量，一行三个
    
    [self prepareBtns];
   
}

-(void)prepareBtns{

    NSInteger count = [_dataDic[@"myValue"] intValue];

    //计算按钮位置
    
    NSInteger row = 0;
    NSInteger column;
    
    NSInteger avgBtnRow = 3;//每行按钮个数
    
    CGFloat margin = 10;
    CGFloat btnW = (ScreenW - margin*(avgBtnRow + 1)) / (avgBtnRow*2);
    CGFloat btnH = btnW;
    CGFloat btnX;
    CGFloat btnY;
    
    for (int i = 0 ; i<count; i++) {
        
        row = i / avgBtnRow;
        column = i % avgBtnRow;
        
        btnX = column * (btnW + margin) + margin;
        btnY = row * (btnH + margin) + margin;
        
        UIButton *btn = [[UIButton alloc]init];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        btn.backgroundColor = [UIColor brownColor];
        
        [btn setImage:[UIImage imageNamed:@"1"] forState:UIControlStateNormal];
        
        [_imagesView addSubview:btn];
        
    }
    
    //设置高度约束
    

    if (count == 0){
        
        //value有可能等于0，过滤掉
        _imagesViewHeight.constant = 0;
    }
    else{
        //此时的row已经循环完了 - 是最终的 count / avgBtnRow 的结果
        _imagesViewHeight.constant = (row + 1) *( btnH + margin) + margin;
    }
}
@end
